/*
 * Copyright (C) 2010, Funcom AS, All Rights Reserved
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 *
 *  @authors
 *  Svein Gunnar Larsen <sveingunnarlarsen@gmail.com>
 *  Erik Thune Lund <culex.eriklund@gmail.com>
 *  Michel Krohn-Dale <kronicz@gmail.com>
 */

package com.funcom.peeler.tool;

import com.funcom.peeler.WorkBench;
import com.funcom.peeler.component.WorkSpace;

import java.awt.*;
import java.awt.event.MouseEvent;

public class PanTool extends Tool {

    private Point prev_coords;
    private Point delta = new Point();

    public PanTool( WorkBench workbench ) {
        super( workbench );
    }

    public void mousePressed( MouseEvent e ) {

        if ( e.getButton() == e.BUTTON1 ) {
            prev_coords = e.getPoint();
        }
    }

    public void mouseReleased( MouseEvent e ) {

        prev_coords = null;
    }

    public void mouseDragged( MouseEvent e ) {

        if ( prev_coords == null ) return;

        updateDelta( e );
        prev_coords = e.getPoint();

        WorkSpace workspace = bui.getWorkSpace().getComponent();
        workspace.setLocation( workspace.getX() + delta.x, workspace.getY() + delta.y );

        clampWorkSpaceBounds();
    }

    private void clampWorkSpaceBounds() {

        WorkSpace workspace = bui.getWorkSpace().getComponent();
        Canvas sceneCanvas = bui.getCanvas();

        int x_loc_max = 0, y_loc_max = 0; // Set bounds for the position of the left and bottom edges of the workspace
        int x_loc_min = -( workspace.getWidth() - sceneCanvas.getWidth() );
        int y_loc_min = -( workspace.getHeight() - sceneCanvas.getHeight() );

        int loc_x = workspace.getX();
        int loc_y = workspace.getY();

        loc_x = loc_x > x_loc_max ? x_loc_max : loc_x;
        loc_x = loc_x < x_loc_min ? x_loc_min : loc_x;

        loc_y = loc_y > y_loc_max ? x_loc_max : loc_y;
        loc_y = loc_y < y_loc_min ? y_loc_min : loc_y;

        workspace.setLocation( loc_x, loc_y );
    }

    public void updateDelta( MouseEvent e ) {

        if ( prev_coords == null ) return;

        delta.x = e.getX() - prev_coords.x;
        delta.y = e.getY() - prev_coords.y;
    }
}
